package org.hamster.common.utils
{
	import mx.collections.ArrayCollection;
	import mx.collections.IList;

	public class CommonUtil
	{
		public function CommonUtil()
		{
		}
		
		public static function toArray(obj:Object):Array
		{
			if (obj == null) {
				return [];
			} else if (obj is Array) {
				return obj as Array;
			} else if (obj is IList) {
				return IList(obj).toArray();
			} else {
				return [obj];
			}
		}
		
		public static function toArrCol(obj:Object):ArrayCollection
		{
			if (obj == null) {
				return new ArrayCollection();
			} else if (obj is Array) {
				return new ArrayCollection(obj as Array);
			} else if (obj is ArrayCollection) {
				return ArrayCollection(obj);
			} else if (obj is IList) {
				var result:ArrayCollection = new ArrayCollection();
				result.addAll(IList(obj));
				return result;
			} else {
				return new ArrayCollection([obj]);
			}
		}
		
		public static function xmlEquals(xml1:XML, xml2:XML):Boolean
		{
			if (xml1 == null || xml2 == null) {
				return false;
			}
			var str1Arr:Array = xml1.toXMLString().split('\n');
			var str2Arr:Array = xml2.toXMLString().split('\n');
			
			for each (var l1:String in str1Arr) {
				var idx:int = str2Arr.indexOf(l1);
				if (idx == -1) {
					return false;
				} else {
					str2Arr[idx] = "";
				}
			}
			
			return str2Arr.join("") == "";
		}
		
		public function convertTo(str:String, type:String):*
		{
			if (type == "boolean" || type == "bool") {
				var boolStr:String = str.toLocaleLowerCase();
				if (str == "true" || str == "y") {
					return true;
				} else {
					return false;
				}
			} else if (type == "int" || type == "number") {
				return parseFloat(str);
			} else if (type == "date") {
				return new Date(parseFloat(str));
			} else {
				return str;
			}
		}
		
	}
}